﻿addLayuiApp("tree");
var checkIdsAll = [],
    checkIdsSub = [],
    menuTree;
addLayuiUseEvent(function () {
    menuTree = layui.tree;
    jqJsonPost("/api/apirole/GetMenuTree",
        null,
        function (data) {
            if (data.code != 0) {
                layer.msg(data.msg);
            } else {
                initTree(data.data);
            }
        });
});
beforeSaveHandler = function (data) {
    getTreeChecked();
    data["Menus"] = checkIdsAll.join(',');
    data["MenusSet"] = checkIdsSub.join(',');
    return data;
}
function getTreeChecked() {
    checkIdsAll = [];
    checkIdsSub = [];
    var checkedData = menuTree.getChecked('treeId');
    $.each(checkedData, function (index, v1) {
        checkIdsAll.push(v1.id);
        if (v1.children) {
            $.each(v1.children, function (index, v2) {
                checkIdsAll.push(v2.id);
                if (v2.children) {
                    $.each(v2.children, function (index, v3) {
                        checkIdsAll.push(v3.id);
                        checkIdsSub.push(v3.id);
                    });
                } else {
                    checkIdsSub.push(v2.id);
                }
            });
        } else {
            checkIdsSub.push(v1.id);
        }
    });
}

function initTree(data) {
    menuTree.render({
        elem: '#menuTree'
        , data: data
        , showCheckbox: true  //是否显示复选框
        , id: 'treeId'
    });
    if (formModel.MenusSet) {
        var checkedIds = formModel.MenusSet.split(",");
        menuTree.setChecked('treeId', checkedIds);
    }
}